#include "gamewidget.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QDebug>
#include <QString>
#include <QMessageBox>

GameWidget::GameWidget(QWidget *parent)
    : QWidget(parent)
{
    setWindowTitle("五子棋游戏");   // 设置窗口标题：

    QVBoxLayout* mainLayout = new QVBoxLayout(this);    // 布局管理器 垂直
    board = new BoardWidget(this);           // 新建棋盘对象
    round_widget = new RoundWidget(this);    //新建回合界面

    QHBoxLayout* horizon_layout = new QHBoxLayout(this);    // 水平布局管理器
    QPushButton* btn_new_game = new QPushButton("开始游戏");    // 按钮，开始新游戏

    horizon_layout->addWidget(btn_new_game);
    horizon_layout->addStretch();
    horizon_layout->addWidget(round_widget);

    mainLayout->addLayout(horizon_layout);
    mainLayout->addWidget(board);

    connect(btn_new_game, SIGNAL(clicked()), this, SLOT(restart_game()));
    // 将当前的按钮与当前页面的resart_game()槽函数连接，在槽函数中调用initBoard()

    connect(board,SIGNAL(signalGameOver(int)),round_widget,SLOT(slotGameOver(int)));
    connect(board, SIGNAL(signalGameOver(int)), this, SLOT(showWinner(int)));
    // 这种连接方式才能保证信号与槽连接正确, 不同对象之间信号与槽连接传递消息

    connect(board,&BoardWidget::signalPlayerChanged,round_widget,&RoundWidget::slotPlayerChangeed);
    //更新回合面板的信息

    connect(this,&GameWidget::signalNewGame,round_widget,&RoundWidget::slotNewGame);
    //开启新游戏，回合面板刷新

    connect(round_widget,&RoundWidget::signalTimeOut,this,&GameWidget::slotTimeOut);
    connect(this,&GameWidget::signalTimeOut,board,&BoardWidget::slotTimeOut);
    //处理超时未下棋的问题

}

GameWidget::~GameWidget()
{

}

void GameWidget::showWinner(int winner)
{
    QString playerName;
    if(winner==BoardWidget::WHITE_PIECE)
    {
        playerName = "WINNER : White Player";
    }
    else if(winner==BoardWidget::BLACK_PIECE)
    {
        playerName = "WINNER : Black Player";
    }
    else
    {
        playerName = "Draw!";
    }
    QMessageBox::information(this, "Game Over", playerName, QMessageBox::Ok);
}

void GameWidget::slotTimeOut(int current_chess)
{
    QString playerName;
    if(current_chess==BoardWidget::WHITE_PIECE)
    {
        playerName = "白棋超时！\n"
                     "黑棋获胜！！";
    }
    else if(current_chess==BoardWidget::BLACK_PIECE)
    {
        playerName = "黑棋超时！\n"
                     "白棋获胜！！";
    }
    QMessageBox::information(this, "Time out", playerName, QMessageBox::Ok);
    emit signalTimeOut();
}

void GameWidget::restart_game()
{
    qDebug() << "Restart the game" << endl;
    board->initBoard();
    emit signalNewGame();
}
